/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package amd.core.calculation;

import amd.database.ConnectDB;
import amd.database.DbDocument;
import amd.database.DbTerm;
import amd.database.DbTermDocument;
import amd.database.QueryNoResultException;
import java.util.ArrayList;

/**
 *
 * @author Latifah Dwi Nurachma
 */
public class TfIdfCalculation {

    public static void calculate(ConnectDB conn){
        try {
            int i = 0;
            int j = 0;
            int nDoc = DbDocument.getNDocument(conn);
            int nTerm = DbTerm.getNTerm(conn);
            ArrayList<String> listDoc = DbDocument.getAllIdDocuments(conn);
            ArrayList<String> listTerm = DbTerm.getAllTermContents(conn);
            while (i < nTerm) {
                String termContent = listTerm.get(i);
                int docFrequency = DbTermDocument.getNDocByTermContent(conn, termContent);
                while (j < nDoc) {
                    String idDoc = listDoc.get(j);
                    if (DbTermDocument.isExists(conn, termContent, idDoc)) {
                        int termFrequency = DbTermDocument.getTermFrequency(conn, idDoc, termContent);
                        float weight = calculateWeightTfIdf(termFrequency, docFrequency, nDoc);
                        DbTermDocument.update(conn, idDoc, termContent, weight);
                    }
                    j++;
                }
                j = 0;
                i++;
            }
        } catch (QueryNoResultException ex) {
            System.out.println("- Tidak dapat melakukan pembobotan term: " + ex.toString());
        }
        
    }

    private static float calculateWeightTfIdf(int termFrequency, int docFrequency, int nDocument){
        float weight = (float) (termFrequency * (Math.log10(nDocument/docFrequency)+1));
        return weight;
    }
}
